package com.example.administrator.reader.fragment;

import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.annotation.Nullable;
import android.support.v4.widget.SwipeRefreshLayout;
import android.util.Log;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.BaseAdapter;
import android.widget.CheckBox;
import android.widget.GridView;
import android.widget.ImageView;
import android.widget.TextView;


import com.example.administrator.reader.R;
import com.example.administrator.reader.activity.MainActivity;
import com.example.administrator.reader.element.CZhudaElement;
import com.example.administrator.reader.entity.Novel;
import com.example.administrator.reader.request.BaseRequest;
import com.example.administrator.reader.request.ShelfRequest;
import com.example.administrator.reader.utils.Constants;
import com.example.administrator.reader.utils.MyToast;
import com.example.administrator.reader.utils.UIUtils;
import com.example.administrator.reader.view.BookView;

import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;

/**
 * 书架类
 * Created by Administrator on 2016-09-04.
 */
public class ShelfFragment extends BaseFragment {

    private boolean isDelete;
    private boolean isLongClick;
    //    private ImageView iv_search;
    private TextView tv_finish;


    // Novels集
    public static List<Novel> novels = new ArrayList<>();
    // 选中的novels集
//    public List<Boolean> isChooseds = new ArrayList<>();
    // 书架的请求类
    public ShelfRequest request = new ShelfRequest();
    // GridView展示页面
    private GridView gv;
    // 下拉刷新控件
    private SwipeRefreshLayout srl;
    // 服务器提供的数据名称
    public String url = "shelf.shtml";
    // 下拉刷新UI更新
    public Handler handler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            switch (msg.what) {
                case Constants.OK:
                    //刷新UI

                    bookAdapter.notifyDataSetChanged();

                    srl.setRefreshing(false);
                    break;

                case Constants.ERROR:
                    srl.setRefreshing(false);
                    break;
            }
        }
    };

    private BookAdapter bookAdapter;

    @Override
    protected void setUpContentView() {
        view = View.inflate(UIUtils.getContext(), R.layout.f_shelf, null);
        srl = (SwipeRefreshLayout) view.findViewById(R.id.srl);

        tv_finish = (TextView) view.findViewById(R.id.tv_finish);
    }

    @Override
    protected void setUpView() {
        gv = (GridView) view.findViewById(R.id.gv);
    }

    @Override
    protected void setUpData(Bundle savedInstanceState) {

        // 设置adapter
        setAdapter();

        // 网络请求
        requestFunc();

        // 下拉刷新
        srlFunc();

        // 点击监听
        clickListener();

        // 添加book到书架
        addBook();

    }



    private void addBook() {
        // FIXME
        CityFragment.cZhudaElement.setiBookRefresh(new CZhudaElement.IBookRefresh() {
            @Override
            public void addBookRresh() {
                MyToast.showToast("shef更新啦...");
                new Thread() {
                    @Override
                    public void run() {

                        /**
                         * 另一种方法，可以不要重新请求服务器，而是将已有的nove直接添加进 shelf 的list
                         */

                        reloadData();
                        for (Novel novel : novels) {
                            Log.e("Novel", novel.getId() + "");
                        }
                    }
                }.start();
            }
        });


    }

    private void clickListener() {
        // 完成
        tv_finish.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                /**
                 * 1、进行网络请求，删除字段
                 * 2、刷新界面
                 */


                // 控件的现隐
//                iv_search.setVisibility(View.VISIBLE);
                tv_finish.setVisibility(View.GONE);
                ((MainActivity) getActivity()).getLayout_delete().setVisibility(View.GONE);
                ((MainActivity) getActivity()).getRg().setVisibility(View.VISIBLE);

                isLongClick = false;
                bookAdapter.notifyDataSetChanged();
            }
        });

        // gridview
        gv.setOnItemLongClickListener(new AdapterView.OnItemLongClickListener() {
            @Override
            public boolean onItemLongClick(AdapterView<?> parent, View view, int position, long id) {


                // 控件的现隐
//                iv_search.setVisibility(View.INVISIBLE);
                tv_finish.setVisibility(View.VISIBLE);
                ((MainActivity) getActivity()).getLayout_delete().setVisibility(View.VISIBLE);
                ((MainActivity) getActivity()).getRg().setVisibility(View.GONE);

                isLongClick = true;
                bookAdapter.notifyDataSetChanged();


                return false;
            }
        });


        // 点击删除
        ((MainActivity) getActivity()).getBt_choose_one().setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                MyToast.showToast("删除");
                isDelete = true;
                Iterator iterator = novels.iterator();
                while (iterator.hasNext()) {
                    Novel novel = (Novel) iterator.next();
                    if (novel.isChoosed()) {
                        iterator.remove();
                    }
                }

                bookAdapter.notifyDataSetChanged();

                // TODO ，。删除数据库
            }
        });

        // 点击全选
        ((MainActivity) getActivity()).getBt_choose_all().setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                MyToast.showToast("全选");
            }
        });
    }

    private void srlFunc() {
        // 下拉刷新
        srl.setOnRefreshListener(new SwipeRefreshLayout.OnRefreshListener() {
            @Override
            public void onRefresh() {
                new Thread() {
                    @Override
                    public void run() {

                        for (Novel novel : novels) {
                            Log.e("Novel", novel.getId() + "");
                        }

                        reloadData();
                    }
                }.start();
            }
        });
        // 刷新按钮的颜色变化
        srl.setColorSchemeResources(R.color.red,
                R.color.green,
                R.color.blue);
    }

    private void requestFunc() {
        // 回调处理函数
        request.setInter(new BaseRequest.BaseInter<List<Novel>>() {
            @Override
            public void handleData(List<Novel> data) {
                Message msg = Message.obtain();
                if (data == null) {
                    //处理
                    msg.what = Constants.ERROR;
                } else {
                    //处理
                    msg.what = Constants.OK;
                    novels = data;
                }
                handler.sendMessage(msg);
            }
        });
    }

    private void setAdapter() {
        bookAdapter = new BookAdapter();
        gv.setAdapter(bookAdapter);
    }


    /**
     * 加载数据
     */
    @Override
    public void loadData() {
        request.firstLoad(url);
    }

    /**
     * 重新加载数据
     */
    @Override
    public void reloadData() {
        request.refreshLoad(url);
    }

    /**
     * 页面创建时开始加载数据
     *
     * @param savedInstanceState
     */
    @Override
    public void onActivityCreated(@Nullable Bundle savedInstanceState) {
        super.onActivityCreated(savedInstanceState);
        this.loadData();
    }

    class BookAdapter extends BaseAdapter {
        @Override
        public int getCount() {
            return novels.size();
        }

        @Override
        public Object getItem(int position) {
            return null;
        }

        @Override
        public long getItemId(int position) {
            return 0;
        }

        @Override
        public View getView(final int position, View convertView, final ViewGroup parent) {
            ViewHolder viewHolder;
            if (convertView == null) {
                viewHolder = new ViewHolder();
                convertView = View.inflate(getActivity(), R.layout.item_book, null);
                viewHolder.ivImageView = (ImageView) convertView.findViewById(R.id.iv_book_cover);
                viewHolder.tvTitle = (TextView) convertView.findViewById(R.id.tv_title);
                viewHolder.tvAuthor = (TextView) convertView.findViewById(R.id.tv_author);
                viewHolder.bookView = (BookView) convertView.findViewById(R.id.book);
                viewHolder.ck_choose = (CheckBox) convertView.findViewById(R.id.ck_choose);
                convertView.setTag(viewHolder);
            } else {
                viewHolder = (ViewHolder) convertView.getTag();
            }

            if (viewHolder.ivImageView != null) {
                bitmapUtils.display(viewHolder.ivImageView, novels.get(position).getImgPath());
            }
            viewHolder.tvTitle.setText(novels.get(position).getName());
            viewHolder.tvAuthor.setText(novels.get(position).getAuthor());
            viewHolder.bookView.setiOpenBook(new BookView.IOpenBook() {
                @Override
                public int openBook(View v) {
                    GridView gv = (GridView) v.getParent();
                    int i = gv.indexOfChild(v);
                    Novel currentNovel = ShelfFragment.novels.get(i);
                    return currentNovel.getId();
                }
            });

            // 删除了以后，全部恢复未选状态
            if (isDelete) {
                viewHolder.ck_choose.setChecked(false);
                if (position == getCount() - 1) {
                    isDelete = true;
                }
            }

            if (isLongClick) {
                viewHolder.ck_choose.setVisibility(View.VISIBLE);
            } else {
                viewHolder.ck_choose.setVisibility(View.GONE);
                // 完成了以后，全部恢复未选状态
                viewHolder.ck_choose.setClickable(false);
            }

            viewHolder.ck_choose.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    if (((CheckBox) v).isChecked()) {
                        // 记录选中
                        novels.get(position).setChoosed(true);
                    } else {
                        // 记录取消
                        novels.get(position).setChoosed(false);
                    }
                }
            });

            return convertView;
        }
    }

    public class ViewHolder {
        private ImageView ivImageView;
        private TextView tvTitle;
        private TextView tvAuthor;
        private String imgPath;
        private BookView bookView;
        private CheckBox ck_choose;
    }


}
